package to3;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.awt.Dimension;
import java.awt.Toolkit;


public class OnderhoudFrame extends javax.swing.JFrame{
       private KlantenLijst k1;
       private String selectedKlantnr;
       private OnderdelenLijst o1;
       private List<Dienst> oList;
       
    public OnderhoudFrame() throws IOException {
        
            initComponents();
            setVisible(true);
            oList = new ArrayList<>();
                    ////////SCHERM IN MIDDEN////////
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = this.getSize();

        int windowX = Math.max(0, (screenSize.width  - windowSize.width ) / 2);
        int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);

        this.setLocation(windowX, windowY);
                    ///////////////////////////////
        
            this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
            selectedKlantLabel.setText(selectedKlantnr);
            k1 = new KlantenLijst();
            o1 = new OnderdelenLijst();
            
          try {
            readFile2();
        } catch (IOException ex) {
            Logger.getLogger(ParkerenFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
          fillOnderdelenList();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btn_Reserveer = new javax.swing.JButton();
        btn_Close = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        selectedKlantLabel = new javax.swing.JLabel();
        btn_SelecteerKlant = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        label1 = new java.awt.Label();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField3 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setFocusTraversalPolicyProvider(true);
        setMaximumSize(new java.awt.Dimension(800, 600));
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Onderhoud");

        btn_Reserveer.setText("Betaal");
        btn_Reserveer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ReserveerActionPerformed(evt);
            }
        });

        btn_Close.setText("Hoofdmenu");
        btn_Close.setPreferredSize(new java.awt.Dimension(164, 46));
        btn_Close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CloseActionPerformed(evt);
            }
        });

        jTextField1.setText("Klantnummer");

        jLabel7.setText("geselecteerde klant:");

        selectedKlantLabel.setText("geen");

        btn_SelecteerKlant.setText("selecteer klant");
        btn_SelecteerKlant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_SelecteerKlantActionPerformed(evt);
            }
        });

        jLabel2.setText("Aantal arbeidsuren:");

        jLabel3.setText("Gebruikte onderdelen:");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        label1.setText("aantal:");

        jButton1.setText("voeg toe");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(324, 324, 324)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(125, 125, 125)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(btn_Reserveer)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btn_SelecteerKlant)))
                                .addGap(78, 78, 78)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(selectedKlantLabel)))
                        .addGap(0, 82, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(49, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btn_Close, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(29, 29, 29)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField2)
                                    .addComponent(jComboBox1, 0, 128, Short.MAX_VALUE))
                                .addGap(59, 59, 59)
                                .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)
                                .addGap(58, 58, 58)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(selectedKlantLabel)
                    .addComponent(btn_SelecteerKlant))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel3)
                                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 178, Short.MAX_VALUE)
                                        .addComponent(btn_Reserveer)
                                        .addGap(170, 170, 170))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jButton1)
                                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addComponent(btn_Close, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
    private void writeOnderdelen() throws IOException{
          List<Onderdeel> listO = o1.getOnderdelen();
          FileWriter fw	 = new FileWriter("onderdelen.txt");
  		PrintWriter pw	 = new PrintWriter(fw);
                boolean eersteKeer = false;
  		for (Onderdeel on : listO){
                if(eersteKeer == false){
                    pw.print(on.getOmschrijving() + ", " + on.getPrijsPerAantal() + ", " + on.getAantalVoorraad());
                    eersteKeer = true;
                }
                else{
                    pw.print("\n" + on.getOmschrijving() + ", " + on.getPrijsPerAantal() + ", " + on.getAantalVoorraad());
                }}
  		pw.close();
                fw.close();
    }

    private void btn_CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CloseActionPerformed
        hoofdMenu hM = new hoofdMenu();
        this.dispose();
    }//GEN-LAST:event_btn_CloseActionPerformed
   
    private void btn_ReserveerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ReserveerActionPerformed
        if(jTextField2.getText().matches("[0-9]{1,3}")) {
        if(setKlantnr(selectedKlantnr)){
        BetaalScherm bS = new BetaalScherm();
        bS.setReturnScreen("onderhoud");
        Arbeidsuren au = new Arbeidsuren(Integer.parseInt(jTextField2.getText()));
        au.setKlantnr(selectedKlantnr);
        oList.add(au);
        bS.addList(oList);
        this.dispose();
        }
        }else {
                JOptionPane.showMessageDialog(null, "Vul correct aantal arbeidsuren in",  "Fout", JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_btn_ReserveerActionPerformed

    
    public void updateVoorraad(List<Onderdeel> oList){
        for (Onderdeel o : oList){
            Onderdeel tempO = o1.getOnderdeel(o.getOmschrijving());
            o1.getOnderdeel(o.getOmschrijving()).setAantalVoorraad(o.getAantalVoorraad()-o.getAantal());
        }
        try {
            writeOnderdelen();
        } catch (IOException ex) {
            Logger.getLogger(OnderhoudFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void btn_SelecteerKlantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SelecteerKlantActionPerformed
        setKlantnr(jTextField1.getText());
    }//GEN-LAST:event_btn_SelecteerKlantActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(jTextField3.getText().matches("[0-9]{1,3}")) {
            if(jComboBox1.getSelectedItem() != null) {
            Onderdeel tempO = o1.getOnderdeel(jComboBox1.getSelectedItem().toString());
            if(tempO.getAantalVoorraad() >= Integer.parseInt(jTextField3.getText())){
            tempO.setKlantnr(selectedKlantnr);
            tempO.setAantal(Integer.parseInt(jTextField3.getText()));
            if (oList.contains(tempO)){
                oList.remove(tempO);
            }
            oList.add(tempO);
            fillGebruikList(oList);
        }
            else {
                JOptionPane.showMessageDialog(null, "Er is niet genoeg voorraad",  "Fout", JOptionPane.ERROR_MESSAGE);
            }
            }
            else {
                JOptionPane.showMessageDialog(null, "Geen onderdeel gekozen",  "Fout", JOptionPane.ERROR_MESSAGE);
            }
        }
        else {
                JOptionPane.showMessageDialog(null, "Geen aantal ingevuld",  "Fout", JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
   
        private void readFile2() throws IOException {
                o1.clearOnderdelenLijst();
		FileReader fr = new FileReader("onderdelen.txt");
                BufferedReader br = new BufferedReader(fr);

                    while (true) {
                    String regel = br.readLine();
                    if (regel == null) {
                    break;
                    }
                    Scanner sc = new Scanner(regel);
                    sc.useDelimiter("\\s*,\\s*");
                    String onderdeel = sc.next();
                    String prijsPerAantalString = sc.next();
                    double prijsPerAantal = Double.parseDouble(prijsPerAantalString);
                    String aantal = sc.next();
                    int aantalVoorraad = Integer.parseInt(aantal);
                    o1.addOnderdeel(onderdeel, prijsPerAantal, aantalVoorraad);
                    sc.close();
                    }
        }
    
    public boolean setKlantnr(String nr){
        try {
            readFile();
        } catch (IOException ex) {
            Logger.getLogger(OnderhoudFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (k1.checkNr(nr) == true){
       selectedKlantnr = nr;
       selectedKlantLabel.setText(selectedKlantnr);
       return true;
        }
       else{
            JOptionPane.showMessageDialog(null, "Klant niet bekend!", "FOUT", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    
    private void fillGebruikList(List<Dienst> oList){
        String s = "";
        for (Dienst d1 : oList){
            s = s + d1.getOmschrijving() + "       " + d1.getAantal() + "\n";  
        }
         jTextArea1.setText(s);
    }
    
     private void fillOnderdelenList(){
        List<Onderdeel> tempList = o1.getOnderdelen();
            String s = "";
            for (Onderdeel o: tempList){
                if (o.getAantalVoorraad() > 0){
                s = s + o.getOmschrijving() + ",";
                }
            }
            final String[] sarray = stringtoArray( s, ",");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel() {
            String[] strings = sarray;
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
    }
    
     private String[] stringtoArray( String s, String sep ) {
  // convert a String s to an Array, the elements
  // are delimited by sep
  // NOTE : for old JDK only (<1.4).
  //        for JDK 1.4 +, use String.split() instead
  StringBuffer buf = new StringBuffer(s);
  int arraysize = 1;
  for ( int i = 0; i < buf.length(); i++ ) {
    if ( sep.indexOf(buf.charAt(i) ) != -1 )
      arraysize++;
  }
  String [] elements  = new String [arraysize];
  int y,z = 0;
  if ( buf.toString().indexOf(sep) != -1 ) {
    while (  buf.length() > 0 ) {
      if ( buf.toString().indexOf(sep) != -1 ) {
        y =  buf.toString().indexOf(sep);
        if ( y != buf.toString().lastIndexOf(sep) ) {
          elements[z] = buf.toString().substring(0, y ); 
          z++;
          buf.delete(0, y + 1);
        }
        else if ( buf.toString().lastIndexOf(sep) == y ) {
          elements[z] = buf.toString().substring
            (0, buf.toString().indexOf(sep));
          z++;
          buf.delete(0, buf.toString().indexOf(sep) + 1);
          elements[z] = buf.toString();z++;
          buf.delete(0, buf.length() );
        }
      }
    }
  }
  else {
    elements[0] = buf.toString(); 
  }
  buf = null;
  return elements;
}
     
       private void readFile() throws IOException {
                k1.clearKlantenLijst();
		FileReader fr = new FileReader("klanten.txt");
                BufferedReader br = new BufferedReader(fr);

                    while (true) {
                    String regel = br.readLine();
                    if (regel == null) {
                    break;
                    }
                    Scanner sc = new Scanner(regel);
                    sc.useDelimiter("\\s*,\\s*");
                    String klantnr = sc.next();
                    String voornaam = sc.next();
                    String achternaam = sc.next();
                    String adres = sc.next();
                    String woonplaats = sc.next();
                    String telefoon = sc.next();
                    String email = sc.next();
                    String rekeningnr = sc.next();
                    k1.addKlant(klantnr, voornaam, achternaam, adres, woonplaats, telefoon, email, rekeningnr);
                    
                    sc.close();
                    }
        }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Close;
    private javax.swing.JButton btn_Reserveer;
    private javax.swing.JButton btn_SelecteerKlant;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private java.awt.Label label1;
    private javax.swing.JLabel selectedKlantLabel;
    // End of variables declaration//GEN-END:variables
}
